# 吉凶方位指南系统

import random
import datetime
from datetime import datetime

class DirectionGuide:
    def __init__(self):
        # 初始化方位数据
        self.directions = self._init_directions()
        self.elements = self._init_elements()
        self.bagua = self._init_bagua()
    
    def _init_directions(self):
        """初始化八方位数据"""
        directions = {
            "东": {
                "element": "木",
                "trigram": "震",
                "animal": "青龙",
                "color": "青色",
                "season": "春",
                "planet": "木星",
                "number": 3,
                "characteristics": "生发、创新、活力、成长"
            },
            "南": {
                "element": "火",
                "trigram": "离",
                "animal": "朱雀",
                "color": "红色",
                "season": "夏",
                "planet": "火星",
                "number": 9,
                "characteristics": "热情、扩张、光明、成熟"
            },
            "西": {
                "element": "金",
                "trigram": "兑",
                "animal": "白虎",
                "color": "白色",
                "season": "秋",
                "planet": "金星",
                "number": 7,
                "characteristics": "收敛、坚毅、果断、成熟"
            },
            "北": {
                "element": "水",
                "trigram": "坎",
                "animal": "玄武",
                "color": "黑色",
                "season": "冬",
                "planet": "水星",
                "number": 1,
                "characteristics": "潜藏、智慧、内敛、蓄势"
            },
            "东北": {
                "element": "土",
                "trigram": "艮",
                "animal": "螣蛇",
                "color": "黄色",
                "season": "冬春之交",
                "planet": "土星",
                "number": 8,
                "characteristics": "稳定、停止、保守、巩固"
            },
            "东南": {
                "element": "木火",
                "trigram": "巽",
                "animal": "腾蛇",
                "color": "紫色",
                "season": "春夏之交",
                "planet": "木火星",
                "number": 4,
                "characteristics": "顺从、柔和、渗透、灵活"
            },
            "西南": {
                "element": "土",
                "trigram": "坤",
                "animal": "勾陈",
                "color": "褐色",
                "season": "夏秋之交",
                "planet": "土星",
                "number": 2,
                "characteristics": "包容、柔顺、厚德、承载"
            },
            "西北": {
                "element": "金水",
                "trigram": "乾",
                "animal": "饕餮",
                "color": "银色",
                "season": "秋冬之交",
                "planet": "金水星",
                "number": 6,
                "characteristics": "刚健、领导、创造、权威"
            }
        }
        return directions
    
    def _init_elements(self):
        """初始化五行数据"""
        elements = {
            "木": {
                "nature": "生长",
                "season": "春",
                "direction": "东",
                "color": "青色",
                "generates": "火",
                "controlled_by": "金",
                "characteristics": "生发、向上、伸展、柔韧",
                "associated_organs": "肝、胆",
                "emotions": "怒"
            },
            "火": {
                "nature": "炎热",
                "season": "夏",
                "direction": "南",
                "color": "红色",
                "generates": "土",
                "controlled_by": "水",
                "characteristics": "热情、上升、扩张、活跃",
                "associated_organs": "心、小肠",
                "emotions": "喜"
            },
            "土": {
                "nature": "厚重",
                "season": "季末",
                "direction": "中央",
                "color": "黄色",
                "generates": "金",
                "controlled_by": "木",
                "characteristics": "稳定、中和、承载、包容",
                "associated_organs": "脾、胃",
                "emotions": "思"
            },
            "金": {
                "nature": "收敛",
                "season": "秋",
                "direction": "西",
                "color": "白色",
                "generates": "水",
                "controlled_by": "火",
                "characteristics": "收敛、坚固、清洁、锐利",
                "associated_organs": "肺、大肠",
                "emotions": "悲"
            },
            "水": {
                "nature": "寒冷",
                "season": "冬",
                "direction": "北",
                "color": "黑色",
                "generates": "木",
                "controlled_by": "土",
                "characteristics": "下行、寒冷、滋润、流动",
                "associated_organs": "肾、膀胱",
                "emotions": "恐"
            }
        }
        return elements
    
    def _init_bagua(self):
        """初始化八卦数据"""
        bagua = {
            "乾": {
                "element": "金",
                "direction": "西北",
                "symbol": "天",
                "nature": "刚健",
                "image": "天",
                "number": 6,
                "trigram": "☰",
                "attributes": "创造、领导、力量、父亲"
            },
            "坤": {
                "element": "土",
                "direction": "西南",
                "symbol": "地",
                "nature": "柔顺",
                "image": "地",
                "number": 2,
                "trigram": "☷",
                "attributes": "接受、顺从、包容、母亲"
            },
            "震": {
                "element": "木",
                "direction": "东",
                "symbol": "雷",
                "nature": "动",
                "image": "雷",
                "number": 3,
                "trigram": "☳",
                "attributes": "震动、行动、新生、长子"
            },
            "巽": {
                "element": "木",
                "direction": "东南",
                "symbol": "风",
                "nature": "入",
                "image": "风",
                "number": 4,
                "trigram": "☴",
                "attributes": "柔和、渗透、顺从、长女"
            },
            "坎": {
                "element": "水",
                "direction": "北",
                "symbol": "水",
                "nature": "陷",
                "image": "水",
                "number": 1,
                "trigram": "☵",
                "attributes": "危险、困难、智慧、中子"
            },
            "离": {
                "element": "火",
                "direction": "南",
                "symbol": "火",
                "nature": "丽",
                "image": "火",
                "number": 9,
                "trigram": "☲",
                "attributes": "光明、依附、美丽、中女"
            },
            "艮": {
                "element": "土",
                "direction": "东北",
                "symbol": "山",
                "nature": "止",
                "image": "山",
                "number": 8,
                "trigram": "☶",
                "attributes": "停止、稳定、保守、少子"
            },
            "兑": {
                "element": "金",
                "direction": "西",
                "symbol": "泽",
                "nature": "悦",
                "image": "泽",
                "number": 7,
                "trigram": "☱",
                "attributes": "喜悦、满足、愉快、少女"
            }
        }
        return bagua
    
    def calculate_lucky_directions(self, birth_date, target_date=None):
        """
        计算吉凶方位
        
        参数:
        birth_date: 用户生日，格式为"YYYY-MM-DD"
        target_date: 目标日期，格式为"YYYY-MM-DD"，默认为当天
        
        返回:
        方位吉凶结果
        """
        # 如果未指定目标日期，使用当前日期
        if target_date is None:
            target_date = datetime.now().strftime("%Y-%m-%d")
        
        birth_dt = datetime.strptime(birth_date, "%Y-%m-%d")
        target_dt = datetime.strptime(target_date, "%Y-%m-%d")
        
        # 计算生肖
        chinese_zodiac = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]
        zodiac_index = (birth_dt.year - 4) % 12
        zodiac = chinese_zodiac[zodiac_index]
        
        # 计算命卦
        # 简化计算，实际应用中应使用更复杂的算法
        birth_year_sum = sum(int(digit) for digit in str(birth_dt.year))
        birth_month_sum = birth_dt.month
        birth_day_sum = sum(int(digit) for digit in str(birth_dt.day))
        life_number = (birth_year_sum + birth_month_sum + birth_day_sum) % 9
        if life_number == 0:
            life_number = 9
        
        # 根据命卦确定基础吉凶方位
        # 这里使用简化算法，实际应用中应根据八字或其他传统方法计算
        bagua_mapping = {
            1: "坎", 2: "坤", 3: "震", 4: "巽",
            5: "中", 6: "乾", 7: "兑", 8: "艮", 9: "离"
        }
        
        life_bagua = bagua_mapping.get(life_number, "中")
        
        # 设置随机种子，确保结果的一致性
        seed = (
            birth_dt.year * 10000 + birth_dt.month * 100 + birth_dt.day +
            target_dt.year * 10000 + target_dt.month * 100 + target_dt.day
        )
        random.seed(seed)
        
        # 确定当日吉凶方位
        all_directions = list(self.directions.keys())
        
        # 根据生肖和命卦确定基础吉方位
        lucky_directions_base = []
        
        # 根据生肖确定吉方位
        zodiac_lucky_directions = {
            "鼠": ["东", "南", "东南"],
            "牛": ["西", "北", "西北"],
            "虎": ["东", "南", "东北"],
            "兔": ["东", "南", "东南"],
            "龙": ["西", "南", "西南"],
            "蛇": ["东", "南", "东南"],
            "马": ["西", "南", "西南"],
            "羊": ["东", "北", "东北"],
            "猴": ["西", "北", "西北"],
            "鸡": ["西", "南", "西南"],
            "狗": ["东", "北", "东北"],
            "猪": ["西", "北", "西北"]
        }
        
        lucky_directions_base.extend(zodiac_lucky_directions.get(zodiac, []))
        
        # 根据命卦确定吉方位
        if life_bagua in self.bagua:
            bagua_info = self.bagua[life_bagua]
            lucky_directions_base.append(bagua_info["direction"])
        
        # 根据当日日期调整吉凶方位
        day_of_year = target_dt.timetuple().tm_yday
        seasonal_factor = (day_of_year % 24) + 1  # 24节气简化
        
        # 当日特殊吉方位（根据日期变化）
        daily_lucky_direction = all_directions[day_of_year % len(all_directions)]
        lucky_directions_base.append(daily_lucky_direction)
        
        # 去重
        lucky_directions_base = list(set(lucky_directions_base))
        
        # 确定最终吉凶方位
        lucky_directions = lucky_directions_base[:3]  # 取前3个作为吉方位
        unlucky_directions = [d for d in all_directions if d not in lucky_directions]
        very_unlucky_directions = random.sample(unlucky_directions, min(2, len(unlucky_directions)))  # 取2个作为大凶方位
        
        # 生成方位详细信息
        lucky_direction_details = []
        for direction in lucky_directions:
            dir_info = self.directions[direction].copy()
            dir_info["direction"] = direction
            dir_info["luck_level"] = "吉"
            dir_info["luck_score"] = random.randint(7, 10)  # 7-10分为吉
            dir_info["advice"] = self._generate_lucky_direction_advice(direction, dir_info)
            lucky_direction_details.append(dir_info)
        
        unlucky_direction_details = []
        for direction in very_unlucky_directions:
            dir_info = self.directions[direction].copy()
            dir_info["direction"] = direction
            dir_info["luck_level"] = "凶"
            dir_info["luck_score"] = random.randint(1, 4)  # 1-4分为凶
            dir_info["advice"] = self._generate_unlucky_direction_advice(direction, dir_info)
            unlucky_direction_details.append(dir_info)
        
        # 生成中性方位
        neutral_directions = [d for d in all_directions if d not in lucky_directions and d not in very_unlucky_directions]
        neutral_direction_details = []
        for direction in neutral_directions[:2]:  # 取2个作为中性方位
            dir_info = self.directions[direction].copy()
            dir_info["direction"] = direction
            dir_info["luck_level"] = "中"
            dir_info["luck_score"] = random.randint(5, 6)  # 5-6分为中性
            dir_info["advice"] = self._generate_neutral_direction_advice(direction, dir_info)
            neutral_direction_details.append(dir_info)
        
        # 生成整体建议
        overall_advice = self._generate_overall_direction_advice(
            lucky_direction_details,
            unlucky_direction_details,
            zodiac,
            life_bagua
        )
        
        # 返回结果
        result = {
            "date": target_date,
            "user_info": {
                "birth_date": birth_date,
                "zodiac": zodiac,
                "life_number": life_number,
                "life_bagua": life_bagua
            },
            "lucky_directions": lucky_direction_details,
            "unlucky_directions": unlucky_direction_details,
            "neutral_directions": neutral_direction_details,
            "overall_advice": overall_advice
        }
        
        return result
    
    def _generate_lucky_direction_advice(self, direction, dir_info):
        """生成吉方位建议"""
        advices = [
            f"今日{direction}方位大吉，适合前往{direction}方办事、旅行或会见重要人物。",
            f"{direction}方位受{dir_info['animal']}守护，今日行{direction}方有贵人相助。",
            f"今日{direction}方{dir_info['element']}气旺盛，适合进行与{dir_info['characteristics']}相关的活动。",
            f"佩戴{dir_info['color']}饰物并朝{direction}方行走，可增强今日运势。",
            f"书桌、床头朝{direction}方摆放，有助于提升工作效率和睡眠质量。"
        ]
        return random.choice(advices)
    
    def _generate_unlucky_direction_advice(self, direction, dir_info):
        """生成凶方位建议"""
        advices = [
            f"今日{direction}方位不宜，尽量避免前往{direction}方办事或旅行。",
            f"{direction}方位{dir_info['element']}气受损，今日不宜进行与{dir_info['characteristics']}相关的活动。",
            f"避免在{direction}方进行重要决策或签订合同，可能会遇到阻碍。",
            f"今日不宜穿{dir_info['color']}衣物，避免朝{direction}方出行。",
            f"避免将重要物品放置在房间的{direction}方位，以免带来不利影响。"
        ]
        return random.choice(advices)
    
    def _generate_neutral_direction_advice(self, direction, dir_info):
        """生成中性方位建议"""
        advices = [
            f"{direction}方位今日平平，可进行日常活动，但避免重大决策。",
            f"{direction}方{dir_info['element']}气中和，适合进行稳定和例行的事务。",
            f"前往{direction}方不会带来特别的好运或厄运，保持平常心态即可。",
            f"{direction}方位适合进行冥想或放松活动，调整身心平衡。",
            f"在{direction}方进行的活动将按既定计划进行，不会有太大波动。"
        ]
        return random.choice(advices)
    
    def _generate_overall_direction_advice(self, lucky_directions, unlucky_directions, zodiac, life_bagua):
        """生成整体方位建议"""
        # 获取最吉利和最不吉利的方位
        most_lucky_direction = max(lucky_directions, key=lambda x: x["luck_score"]) if lucky_directions else None
        most_unlucky_direction = min(unlucky_directions, key=lambda x: x["luck_score"]) if unlucky_directions else None
        
        advice = "今日方位指南：\n\n"
        
        # 添加最吉利方位建议
        if most_lucky_direction:
            direction = most_lucky_direction["direction"]
            element = most_lucky_direction["element"]
            animal = most_lucky_direction["animal"]
            advice += f"1. 今日最佳方位是{direction}方，{element}气旺盛，受{animal}守护。建议重要活动朝此方向进行，将获得事半功倍的效果。\n\n"
        
        # 添加最不吉利方位建议
        if most_unlucky_direction:
            direction = most_unlucky_direction["direction"]
            element = most_unlucky_direction["element"]
            advice += f"2. 今日应避开{direction}方，{element}气受损，不宜在此方向进行重要活动或决策，以免遇到阻碍。\n\n"
        
        # 添加生肖相关建议
        zodiac_advices = {
            "鼠": "机敏多变的鼠年人，今日宜保持灵活思维，避免固执己见。",
            "牛": "踏实稳重的牛年人，今日宜按部就班行事，不宜冒进。",
            "虎": "勇猛果敢的虎年人，今日宜适当收敛锋芒，避免冲突。",
            "兔": "温和敏感的兔年人，今日宜关注情感需求，避免过度思虑。",
            "龙": "自信威严的龙年人，今日宜展现领导才能，避免独断专行。",
            "蛇": "智慧深沉的蛇年人，今日宜运用洞察力，避免过度猜疑。",
            "马": "活力四射的马年人，今日宜保持积极行动，避免浮躁。",
            "羊": "温顺随和的羊年人，今日宜展现创造力，避免优柔寡断。",
            "猴": "机智灵活的猴年人，今日宜善用智慧，避免投机取巧。",
            "鸡": "勤勉务实的鸡年人，今日宜注重细节，避免挑剔批评。",
            "狗": "忠诚可靠的狗年人，今日宜坚守原则，避免过度警惕。",
            "猪": "诚实厚道的猪年人，今日宜保持乐观，避免过度放纵。"
        }
        
        advice += f"3. {zodiac_advices.get(zodiac, '今日宜保持平常心，顺其自然。')}\n\n"
        
        # 添加命卦相关建议
        if life_bagua in self.bagua:
            bagua_info = self.bagua[life_bagua]
            advice += f"4. 作为{life_bagua}卦之人，您的本命特质是{bagua_info['nature']}，今日宜发挥{bagua_info['attributes'].split('、')[0]}的特长，调和{bagua_info['element']}之气。\n\n"
        
        # 添加一般性建议
        advice += "5. 一般建议：\n"
        advice += "   - 重要会议或谈判桌椅摆放应避开不利方位\n"
        advice += "   - 办公桌或床头朝向宜选吉利方位\n"
        advice += "   - 出行时尽量选择吉利方向出发\n"
        advice += "   - 佩戴与吉利方位相关的颜色饰物可增强运势\n"
        advice += "   - 记住方位吉凶每日变化，定期查询以获得最佳指引"
        
        return advice

# 使用示例
if __name__ == "__main__":
    direction_guide = DirectionGuide()
    result = direction_guide.calculate_lucky_directions(
        birth_date="1990-01-15",
        target_date="2025-05-28"
    )
    print(result)
